
import datetime


from TasK.models import Tag, Production, Chantier, Fonctionalite, Tache, TacheDevTime, Cycle, TachesDuCycle
from django.contrib import admin


class LinkedInline(admin.TabularInline):
    '''
    I use this inline to add the link to the entity on each
    inline row.
    '''
    template = "admin/edit_inline/linked.html"
    admin_model_path = None

    @property
    def edit_pk(self):
        return 5
    
    def __init__(self, *args):
        super(LinkedInline, self).__init__(*args)
        if self.admin_model_path is None:
            self.admin_model_path = self.model.__name__.lower()

class TaggedInline(LinkedInline):
    admin_model_path = "tache"
    model = Tache.tags.through
    extra = 3
    can_delete = False

class TagAdmin(admin.ModelAdmin):
    inlines = [TaggedInline]
admin.site.register(Tag, TagAdmin)

class ProdTachesInline(LinkedInline):
    admin_model_path = "tache"
    model = Tache.productions.through
    extra = 3
    can_delete = False

class ProductionAdmin(admin.ModelAdmin):
    inlines = [ProdTachesInline]
admin.site.register(Production, ProductionAdmin)

class FonctionaliteInline(LinkedInline):
    admin_model_path = "fonctionalite"
    model = Fonctionalite
    #fk_name = 'chantier'
    extra = 3
    fields = ['name'] 

    can_delete = False

class ChantierAdmin(admin.ModelAdmin):
    #list_display = ['name']
    inlines = [FonctionaliteInline]
admin.site.register(Chantier, ChantierAdmin)

class TacheInline(LinkedInline):
    admin_model_path = "tache"
    model = Tache
    #fk_name = 'fonctionalite'
    extra = 0
    fields = ['name', 'creator', 'length', 'status', 'spent', 'priority', 'create_date'] 
    readonly_fields = ['name', 'creator', 'length', 'spent', 'create_date']

    can_delete = False

class FonctionaliteAdmin(admin.ModelAdmin):
    #-- Fonctionalite List page
    list_display = ['name','chantier', 'status']
    #list_editable = ['chantier', 'name']
    ordering = ['name']
    list_filter = ['chantier']
    search_fields = ['chantier__name', 'name']
    #filter_vertical = ['name']
    
    #-- Fonctionalite Edit/Create page
    
    #fieldsets = [
    #    (None,      {'fields': ['chantier', 'name']}),
    #]
    inlines = [TacheInline]
        
    #-- Actions
    
    def Export_to_intranet(self, request, queryset):
        #rows_updated = queryset.update(status='p')
        #if rows_updated == 1:
        #    message_bit = "1 story was"
        #else:
        #    message_bit = "%s stories were" % rows_updated
        self.message_user(request, "This action is just a dummy (ran on %i objects)." % len(queryset))
    actions = ['Export_to_intranet']
admin.site.register(Fonctionalite, FonctionaliteAdmin)


class TachesDuCycleAdmin(LinkedInline):
    admin_model_path = 'tache'
    model = TachesDuCycle
    extra = 1
    can_delete = True

class TacheDevTimeInline(admin.TabularInline):
    model = TacheDevTime
    extra = 1
    can_delete = True


class TacheAdmin(admin.ModelAdmin):
    list_display = ['fonctionalite', 'name', 'creator', 'length', 'in_current_cycle', 'status', 'spent', 'priority', 'create_date', 'start_date']
    readonly_fields = ['creator', 'in_current_cycle', 'create_date']
    list_display_links = ['name']
    ordering = ['priority']
    list_filter = ['fonctionalite', 'status', 'dev', 'creator']
    search_fields = ['fonctionalite__name', 'name']

    fieldsets = [
        (None,      {
                    'fields': [('fonctionalite', 'name'), ('start_date',), ('status', 'length',), ('description',)],
                    
                    }
        ),
        ('More infos...',{
                    'fields': ['creator', 'create_date', 'priority'],
                    'classes': ['collapse']
                    }
        ),
        ('Tags and Pros',{
                    'fields': ['tags', 'productions'],
                    'classes': ['collapse']
                    }
        ),
    ]
    inlines = [TacheDevTimeInline]

    def Clone_Task(self, request, queryset):
        self.message_user(request, "NOT IMPLEMENTED (clone %i tasks)." % len(queryset))

    def Create_Cycle(self, request, queryset):
        newCycle = Cycle.objects.create(
            name='The Cycle', 
            start_date=datetime.date.today(), 
            end_date=datetime.date.today() + datetime.timedelta(days=Cycle.default_len)
        )
        for tache in queryset:
            asso = TachesDuCycle( tache=tache, cycle=newCycle, priority=50 )
            if tache.status == 'INV':
                tache.status = 'WAIT'
                tache.save()
            asso.save()

        self.message_user(request, "NOT IMPLEMENTED (Create cycle with %i tasks)." % len(queryset))
    actions = ['Clone_Task', 'Create_Cycle']
admin.site.register(Tache, TacheAdmin)


class CycleAdmin(admin.ModelAdmin):
    #-- Cycle List page
    list_display = ['name', 'status', 'start_date', 'end_date', 'count', 'length', 'spent', 'comments']
    list_editable = ['status', 'start_date', 'end_date',]
    list_display_links = ['name']
    ordering = ['start_date']
    date_hierarchy = 'start_date'
    list_filter = ['status']
    search_fields = ['name', 'status', 'comments']
    #filter_vertical = ['name']
    
    #-- Cycle Edit/Create page
    inlines = [TachesDuCycleAdmin]
        
    #-- Actions
    def Export_to_intranet(self, request, queryset):
        self.message_user(request, "NOT YET IMPLEMENTED. Report %i cycles to intranet." % len(queryset))

    def Create_cycle_with_task_not_done_in_selected_cycles(self, request, queryset):
        self.message_user(request, "NOT YET IMPLEMENTED. Report %i cycles to intranet." % len(queryset))
        newCycle = Cycle.objects.create(
            name='The Finisher Cycle', 
            start_date=datetime.date.today(), 
            end_date=datetime.date.today() + datetime.timedelta(days=Cycle.default_len)
        )
        for cycle in queryset:
            for tache in cycle.taches.exclude(status='DONE'):
                print tache, tache.status
#            asso = TachesDuCycle( tache=tache, cycle=newCycle, priority=50 )
#            asso.save()

    actions = ['Export_to_intranet', 'Create_cycle_with_task_not_done_in_selected_cycles']
    
admin.site.register(Cycle, CycleAdmin)

